package cn.josh.action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.josh.bean.Ec_user;
import cn.josh.service.Ec_userService;
import cn.josh.servicelmpl.Ec_userServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{

		//取得前端输入的账号密码
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		System.out.println("用户名:" + userName + "\n" + "密码：" + password);
		
		//将数据封装
		Ec_user user = new Ec_user();
		user.setLogin_name(userName);
		user.setPassword(password);
		
		//将封装成的对象传给数据库操作类
		Ec_userService user_ser = new Ec_userServiceImpl();
		Ec_user userBack = user_ser.login(user);
		
		if(userBack == null)
		{
			response.getWriter().append("<script>alert('账号不存在!');window.location.href='/ShoppingWebsite/jsp/login.jsp'</script>");
		}
		else if(userBack.getPassword().equals(user.getPassword()))
		{
			// 把生成的用户对象保存到session域对象中
			HttpSession session = request.getSession();
			// 将对象存入session域
			session.setAttribute("userName", userBack.getName());
			session.setAttribute("userId", userBack.getId());
			
			response.sendRedirect("/ShoppingWebsite/IndexServlet");	
		}
		else
		{
			response.getWriter().append("<script>alert('密码错误!');window.location.href='/ShoppingWebsite/jsp/login.jsp'</script>");
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
		doGet(request, response);
	}

}
